package com.tzy.note.base.thread.create;

import com.tzy.note.base.util.Downloader;

import java.util.concurrent.*;

/**
 * 实现Callable接口多线程下载
 * 1.有返回值
 * 2.可以抛异常
 */
public class CreateThread3_DownLoader implements Callable {
    //网络资源url
    private String url;
    //保存的文件名(含路径)
    private String pathFileName;

    public CreateThread3_DownLoader(String url,String pathFileName){
        this.url = url;
        this.pathFileName = pathFileName;
    }

    @Override
    public Boolean call() throws Exception {
        if("tzy3".equals(Thread.currentThread().getName())){
            System.out.println("线程: " + Thread.currentThread().getName() + " 下载了" + pathFileName + "失败！");
            return false;
        }
        Downloader.download(url,pathFileName);
        System.out.println("线程: " + Thread.currentThread().getName() + " 下载了" + pathFileName + "成功！");
        return true;
    }

    public static void main(String[] args) throws Exception {
        CreateThread3_DownLoader cd1 = new CreateThread3_DownLoader("https://www.baidu.com/favicon.ico","1.ico");
        CreateThread3_DownLoader cd2 = new CreateThread3_DownLoader("https://www.baidu.com/img/flexible/logo/pc/result.png","2.png");
        CreateThread3_DownLoader cd3 = new CreateThread3_DownLoader("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/topnav/baiduyun@2x-e0be79e69e.png","3.png");

        FutureTask<Boolean> futureTask1 = new FutureTask<>(cd1);
        new Thread(futureTask1,"tzy1").start();
        //阻塞等待整个线程执行完成，获取返回结果
        System.out.println(futureTask1.get());

        FutureTask<Integer> futureTask2 = new FutureTask<>(cd2);
        new Thread(futureTask2,"tzy2").start();
        System.out.println(futureTask2.get());

        FutureTask<Integer> futureTask3 = new FutureTask<>(cd3);
        new Thread(futureTask3,"tzy3").start();
        System.out.println(futureTask3.get());
    }
}
